#include "bt_hal.h"
#include <signal.h>
#define ARRAYSIZE(a) (sizeof(a) / sizeof(*(a)))

static btmg_callback_t *bt_callback = NULL;
ble_gatt_data_t ble_list[BLE_NUM_LIMIT] = {0};

ble_gatt_data_t *get_addr_from_id(uint16_t conn_hdl)
{
    for (int i = 0; i < BLE_NUM_LIMIT; i++)
    {
        if (ble_list[i].conn_id == conn_hdl)
        {
            return &ble_list[i];
        }
    }
    return NULL;
}

uint8_t add_device_to_list(ble_gatt_data_t device)
{
    for (int i = 0; i < BLE_NUM_LIMIT; i++)
    {
        if (ble_list[i].conn_id == -1)
        {
            ble_list[i] = device;
            return 0;
        }
    }
    return 1;
}
void del_device_to_list(int conn_id)
{
    for (int i = 0; i < BLE_NUM_LIMIT; i++)
    {
        if (ble_list[i].conn_id == conn_id)
        {
            bzero(&ble_list[i], sizeof(ble_gatt_data_t));
            return;
        }
    }
    return;
}

uint8_t get_device_from_id(uint16_t conn_hdl)
{
    for (int i = 0; i < BLE_NUM_LIMIT; i++)
    {
        if (ble_list[i].conn_id == conn_hdl)
        {
            return 1;
        }
    }
    return 0;
}

void bt_register_callback(void)
{
    bt_gatt_server_register_callback(bt_callback);
    // bt_gatt_client_register_callback(bt_callback);
}


int bt_init(void)
{
    printf("\033[1;34m chenql%d \033[0m\n", __LINE__);
    for (int i = 0; i < BLE_NUM_LIMIT; i++)
    {
        ble_list[i].conn_id = -1;
    }
    system("/etc/bluetooth/bt_init.sh stop");
    system("/etc/bluetooth/bt_init.sh stop");
    btmg_set_log_file_path("/tmp/btmg.log");
    if (bt_manager_preinit(&bt_callback) != 0)
    {
        printf("bt preinit failed!\n");
        return -1;
    }
    int profile = BTMG_GATT_SERVER_ENABLE;
    bt_manager_enable_profile(profile);
    if (bt_manager_init(bt_callback) != 0)
    {
        printf("bt manager init failed.\n");
        return -1;
    }
    system("/etc/bluetooth/bt_init.sh ble_start");
    bt_manager_gatt_server_init();
    // bt_manager_gatt_client_init();
    bt_register_callback();
    printf("\033[1;34m chenql%d \033[0m\n", __LINE__);

    return 0;
}

int bt_deinit(void)
{
    BTMG_INFO("ENTER...");
    bt_manager_gatt_server_deinit();
    // bt_manager_gatt_client_deinit();
    system("/etc/bluetooth/bt_init.sh stop");
    bt_manager_deinit(bt_callback);
    btmg_log_stop();
    BTMG_INFO("ENTER2...");
    return 0;
}
